package com.example.steveaoblogdemo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.steveaoblogdemo.entity.Articles;
import com.example.steveaoblogdemo.entity.Tag;
import com.example.steveaoblogdemo.mapper.TagMapper;
import com.example.steveaoblogdemo.service.TagService;
import com.example.steveaoblogdemo.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {
    @Resource
    TagMapper tagMapper;

    public Result<?> queryTag(){
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",0);
        List<Tag> list = tagMapper.selectList(queryWrapper);
        return new Result<>(200,"查询成功",list);
    }

    public Result<?> query(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String search){
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(search)){
            queryWrapper.eq("status",0).like("t_name",search);
        }
        queryWrapper.eq("status",0);
        IPage<Tag> tagIPage = tagMapper.selectPage(new Page<>(pageNum,pageSize),queryWrapper);
        return new Result<>(200,"查询成功",tagIPage);
    }

    public int addTag(@RequestParam Integer id,@RequestParam String tName){
        tagMapper.addTag(id,tName);
        return 0;
    }

    public int updateTag(@RequestParam String tName,@RequestParam Integer id){
        tagMapper.updateTag(tName,id);
        return 0;
    }

    public Result<?> deleteTag(@RequestParam Integer id){
        UpdateWrapper<Tag> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id).set("status",1);
        int result = tagMapper.update(null,wrapper);
        return new Result<>(200,"删除成功",result);
    }

    public Result<?> queryById(@RequestParam Integer id){
        QueryWrapper<Tag> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        Tag tag = tagMapper.selectOne(wrapper);
        if (tag!=null){
            return new Result<>(200,"查询成功",tag);
        }
        return new Result<>(400,"查询失败",null);
    }

    public Result<?> queryByTag(@RequestParam Integer id){

      List<Articles> articles = tagMapper.query(id);
      if (articles.size()>0){
          return new Result<>(200,"查询成功",articles);
      }
      return new Result<>(400,"查询失败",null);
    }
}
